package com.golddaymicromall.activity.setting.personal.bankcard;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.golddaymicromall.activity.R;
import com.golddaymicromall.application.MyApplication;
import com.golddaymicromall.base.BaseActivity;
import com.golddaymicromall.bean.AreaInfo;
import com.golddaymicromall.bean.BankInfo;
import com.golddaymicromall.bean.CityInfo;
import com.golddaymicromall.bean.ProvinceInfo;
import com.golddaymicromall.util.RopUtils;
import com.golddaymicromall.util.SPUtils;
import com.golddaymicromall.util.ServerConfig;
import com.google.common.collect.Maps;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.convert.StringConvert;
import com.lzy.okrx.RxAdapter;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import rx.android.schedulers.AndroidSchedulers;

public class NewAddBankCardActivity extends BaseActivity implements View.OnClickListener {

    private List<BankInfo> bankInfo = null;
    private List<ProvinceInfo> provinceInfo = null;
    private List<CityInfo> cityInfo = null;
    private List<AreaInfo> areaInfo = null;
    private Spinner mBankCountry;
    private Spinner mBankProvince;
    private Spinner mBankCity;
    private Spinner mBankArea;
    private Spinner mbanktype;
    private LinearLayout mNewAddBankBack;
    private CheckBox mbankcb1;
    private Button mbankbtn1;
    private String provinceId;
    private String cityId;
    private String areaId;
    private String bankId;
    private EditText mbanknumber;
    private EditText musername;

    private String flag = "1";
    private String mbanknumbers;
    private String musernames;
    private String Customerno;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_add_bank_card);
        Customerno = SPUtils.get(getApplicationContext(), "Customerno", "").toString();
        attemptGetProvinceTask();
        attemptBackInfo();
        initView();
    }

    private void initView() {
        mBankProvince = (Spinner) findViewById(R.id.BankProvince);
        mBankCity = (Spinner) findViewById(R.id.bankCity);
        mBankArea = (Spinner) findViewById(R.id.bankArea);
        mbanktype = (Spinner) findViewById(R.id.banktype);
        mbankbtn1 = (Button) findViewById(R.id.bankbtn1);
        mbanknumber = (EditText) findViewById(R.id.banknumber);
        musername = (EditText) findViewById(R.id.username);
        mbankcb1 = (CheckBox) findViewById(R.id.bankcb1);
        mNewAddBankBack = (LinearLayout) findViewById(R.id.newAddBank_back);
        mNewAddBankBack.setOnClickListener(this);
        mbankbtn1.setOnClickListener(this);
    }

    public void attemptBackInfo() {
        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.dictionnary.get");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("parentid", "535");
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);
        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s -> {
                    if (!"".equals(s)) {
                        if (s.contains("errorToken") || "0".equals(s)) {
                            Toast.makeText(getApplicationContext(), "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                        } else if ("null".equals(s)) {
                            Toast.makeText(getApplicationContext(), "暂无数据", Toast.LENGTH_SHORT).show();
                        } else {
                            bankInfo = JSON.parseArray(s, BankInfo.class);
                            final List<String> listbank = new ArrayList<String>();
                            for (int i = 0; i < bankInfo.size(); i++) {
                                listbank.add(bankInfo.get(i).getName());
                            }
                            // adpater对象
                            final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(NewAddBankCardActivity.this, android.R.layout.simple_spinner_dropdown_item, listbank);
                            mbanktype.setAdapter(arrayAdapter);
                            mbanktype.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                @Override
                                public void onItemSelected(AdapterView<?> parent, View view,
                                                           int position, long id) {
                                    Spinner spinner = (Spinner) parent;
                                    for (int i = 0; i < bankInfo.size(); i++) {
                                        if (spinner.getItemAtPosition(position).toString().equals(bankInfo.get(i).getName())) {
                                            bankId = bankInfo.get(i).getTextvalue();
                                        }
                                    }
                                }

                                @Override
                                public void onNothingSelected(AdapterView<?> parent) {
                                    Toast.makeText(getApplicationContext(), "没有改变的处理",
                                            Toast.LENGTH_LONG).show();
                                }
                            });
                        }
                    } else {
                        Toast.makeText(getApplicationContext(), "没有请求到数据,请稍后重试", Toast.LENGTH_SHORT).show();
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                });

    }


    private void attemptbankinfoEditbefore() {
        if (mbankcb1.isChecked()) {
            flag = "0";
        } else {
            flag = "1";
        }
        String logid = SPUtils.get(getApplicationContext(), "Id", "").toString();
        mbanknumbers = mbanknumber.getText().toString().trim();
        musernames = musername.getText().toString().trim();
        if (mbanknumbers.length() != 19) {
            Toast.makeText(this, "银行账户必须为19位", Toast.LENGTH_SHORT).show();
            return;
        }
        if ("".equals(mbanknumbers)) {
            Toast.makeText(this, "卡号不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if ("".equals(musernames)) {
            Toast.makeText(this, "用户名不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (isSpecial(musernames)) {
            Toast.makeText(this, "用户名不能输入特殊字符", Toast.LENGTH_SHORT).show();
            return;
        }
        attemptbankinfoEdit(logid, mbanknumbers, musernames, provinceId, cityId, areaId, bankId, flag);

    }

    private void attemptbankinfoEdit(String logId, String mbanknumbers, String musernames, String provinceId, String cityId, String areaId, String bankId, String flag) {
        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.bank.add");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("customerid", logId);
        form.put("bankProvince", provinceId);
        form.put("bankCity", cityId);
        form.put("bankArea", areaId);
        form.put("bankNo", mbanknumbers);
        form.put("bankName", bankId);
        form.put("bankUsername", musernames);
        form.put("status", flag);
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);
        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s -> {
                    if (!"".equals(s)) {
                        if (s.contains("errorToken") || "0".equals(s)) {
                            Toast.makeText(getApplicationContext(), "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                        } else if ("null".equals(s)) {
                            Toast.makeText(getApplicationContext(), "暂无数据", Toast.LENGTH_SHORT).show();
                        } else {


                            if (Integer.parseInt(s) == -1) {
                                Toast.makeText(NewAddBankCardActivity.this, "信息不完整，请添加", Toast.LENGTH_SHORT).show();
                            } else if (Integer.parseInt(s) == 0) {
                                Toast.makeText(NewAddBankCardActivity.this, "添加失败", Toast.LENGTH_SHORT).show();
                            } else if (Integer.parseInt(s) == 1) {
                                Toast.makeText(NewAddBankCardActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
                                finish();
                                MyApplication.getInstance().attemptRiZhi(Customerno, "银行卡添加");
                            }


                        }
                    } else {
                        Toast.makeText(getApplicationContext(), "没有请求到数据,请稍后重试", Toast.LENGTH_SHORT).show();
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                });


    }

    public boolean isSpecial(String bz) {
        String regEx = "[`~!@#$%^&*()+=|{}':;'\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(bz);
        return m.find();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bankbtn1:
                attemptbankinfoEditbefore();
                break;
            case R.id.newAddBank_back:
                finish();
                break;
            default:
                break;
        }
    }


    private void attemptGetProvinceTask() {
        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.address.getprovinces");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);
        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s -> {
                    if (!"".equals(s)) {
                        if (s.contains("errorToken") || "0".equals(s)) {
                            Toast.makeText(getApplicationContext(), "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                        } else if ("null".equals(s)) {
                            Toast.makeText(getApplicationContext(), "暂无数据", Toast.LENGTH_SHORT).show();
                        } else {
                            provinceInfo = JSON.parseArray(s, ProvinceInfo.class);
                            final List<String> listProvince = new ArrayList<String>();
                            for (int i = 0; i < provinceInfo.size(); i++) {
                                listProvince.add(provinceInfo.get(i).getName());
                            }
                            // adpater对象
                            final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(NewAddBankCardActivity.this, android.R.layout.simple_spinner_dropdown_item, listProvince);

                            mBankProvince.setAdapter(arrayAdapter);
                            mBankProvince.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                @Override
                                public void onItemSelected(AdapterView<?> parent, View view,
                                                           int position, long id) {
                                    Spinner spinner = (Spinner) parent;
                                    for (int i = 0; i < provinceInfo.size(); i++) {
                                        if (spinner.getItemAtPosition(position).toString().equals(provinceInfo.get(i).getName())) {
                                            provinceId = provinceInfo.get(i).getId();
                                            attemptGetCityTask(provinceId);
                                        }
                                    }
                                }

                                @Override
                                public void onNothingSelected(AdapterView<?> parent) {
                                    Toast.makeText(getApplicationContext(), "没有改变的处理",
                                            Toast.LENGTH_LONG).show();
                                }
                            });
                        }
                    } else {
                        Toast.makeText(getApplicationContext(), "没有请求到数据,请稍后重试", Toast.LENGTH_SHORT).show();
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                });
    }

    private void attemptGetCityTask(String provinceId) {
        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.address.getcity");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("province", provinceId);
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);
        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s -> {
                    if (!"".equals(s)) {
                        if (s.contains("errorToken") || "0".equals(s)) {
                            Toast.makeText(getApplicationContext(), "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                        } else if ("null".equals(s)) {
                            Toast.makeText(getApplicationContext(), "暂无数据", Toast.LENGTH_SHORT).show();
                        } else {
                            cityInfo = JSON.parseArray(s, CityInfo.class);
                            final List<String> listCity = new ArrayList<String>();
                            for (int i = 0; i < cityInfo.size(); i++) {
                                listCity.add(cityInfo.get(i).getName());
                            }
                            // adpater对象
                            final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(NewAddBankCardActivity.this, android.R.layout.simple_spinner_dropdown_item, listCity);
                            mBankCity.setAdapter(arrayAdapter);
                            mBankCity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                @Override
                                public void onItemSelected(AdapterView<?> parent, View view,
                                                           int position, long id) {
                                    Spinner spinner = (Spinner) parent;
                                    for (int i = 0; i < cityInfo.size(); i++) {
                                        if (spinner.getItemAtPosition(position).toString().equals(cityInfo.get(i).getName())) {
                                            cityId = cityInfo.get(i).getId();
                                            attemptGetAreaTask(cityId);
                                        }
                                    }
                                }

                                @Override
                                public void onNothingSelected(AdapterView<?> parent) {
                                    Toast.makeText(getApplicationContext(), "没有改变的处理",
                                            Toast.LENGTH_LONG).show();
                                }
                            });


                        }
                    } else {
                        Toast.makeText(getApplicationContext(), "没有请求到数据,请稍后重试", Toast.LENGTH_SHORT).show();
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                });


    }

    private void attemptGetAreaTask(String cityId) {
        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.address.getdistrict");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("city", cityId);
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);
        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s -> {
                    if (!"".equals(s)) {
                        if (s.contains("errorToken") || "0".equals(s)) {
                            Toast.makeText(getApplicationContext(), "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                        } else if ("null".equals(s)) {
                            Toast.makeText(getApplicationContext(), "暂无数据", Toast.LENGTH_SHORT).show();
                        } else {
                            areaInfo = JSON.parseArray(s, AreaInfo.class);
                            final List<String> listArea = new ArrayList<String>();
                            for (int i = 0; i < areaInfo.size(); i++) {
                                listArea.add(areaInfo.get(i).getName());
                            }
                            // adpater对象
                            final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(NewAddBankCardActivity.this, android.R.layout.simple_spinner_dropdown_item, listArea);
                            mBankArea.setAdapter(arrayAdapter);
                            mBankArea.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                @Override
                                public void onItemSelected(AdapterView<?> parent, View view,
                                                           int position, long id) {
                                    Spinner spinner = (Spinner) parent;
                                    for (int i = 0; i < areaInfo.size(); i++) {
                                        if (spinner.getItemAtPosition(position).toString().equals(areaInfo.get(i).getName())) {
                                            areaId = areaInfo.get(i).getId();
                                        }
                                    }
                                }

                                @Override
                                public void onNothingSelected(AdapterView<?> parent) {
                                    Toast.makeText(getApplicationContext(), "没有改变的处理",
                                            Toast.LENGTH_LONG).show();
                                }
                            });

                        }
                    } else {
                        Toast.makeText(getApplicationContext(), "没有请求到数据,请稍后重试", Toast.LENGTH_SHORT).show();
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                });
    }


}
